package com.example.communication;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @author zhangs
 * @version v1.0
 * @decription LockSupport.park/unpark
 * @date 2021/3/28 13:13
 **/
public class ParkAndUnPark {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            Thread curr = Thread.currentThread();
            System.out.println(curr.getName() + " start!");
            // 挂起当前线程等待许可
            LockSupport.park(curr);
            System.out.println(curr.getName() + " end!");
        }, "t1");

        Thread t2 = new Thread(() -> {
            Thread curr = Thread.currentThread();
            System.out.println(curr.getName() + " start!");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 给t1线程授予许可
            LockSupport.unpark(t1);
            System.out.println(curr.getName() + " end!");
        }, "t2");

        t1.start();
        t2.start();
    }
}
